package com.my.zl.console.controller.generator;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.my.zl.common.dto.ReqDTO;
import com.my.zl.common.dto.ResDTO;
import com.my.zl.common.enums.resp.GlobalEnum;
import com.my.zl.common.exception.BizException;
import com.my.zl.common.utils.FreemarkerTool;
import com.my.zl.console.common.aop.NoLogAnnotation;
import com.my.zl.console.common.config.MyselfProperties;
import com.my.zl.console.common.utils.generator.ReaderData;
import com.my.zl.console.common.utils.generator.ZLGenerator;
import com.my.zl.console.common.utils.generator.bean.CfgConfig;
import com.my.zl.console.common.utils.generator.bean.CfgMethodEntity;
import com.my.zl.console.common.utils.generator.bean.ZLConfig;
import com.my.zl.console.controller.base.BaseController;
import com.my.zl.console.dto.generator.ReqCodeGenereatorDTO;
import com.my.zl.console.dto.generator.ReqLoadTableDTO;
import com.my.zl.console.dto.generator.ReqLoadTemplateDTO;
import com.my.zl.console.dto.generator.ReqProjectFileDTO;
import com.my.zl.console.dto.generator.ReqTemplateContentDTO;
import com.my.zl.console.dto.generator.ReqTemplateViewShowDTO;
import com.my.zl.console.dto.generator.ReqUploadProjectDTO;
import com.my.zl.console.dto.generator.ResCodeGenereatorDTO;
import com.my.zl.console.dto.generator.ResLoadTableDTO;
import com.my.zl.console.dto.generator.ResLoadTemplateDTO;
import com.my.zl.console.dto.generator.ResProjectFileDTO;
import com.my.zl.console.dto.generator.ResTemplateContentDTO;
import com.my.zl.console.dto.generator.ResTemplateViewShowDTO;
import com.my.zl.console.dto.generator.ResUploadProjectDTO;
import com.my.zl.console.dto.generator.TemplateDtlVO;
import com.my.zl.console.dto.generator.CodeGenereatorDTO.FileListDTO;
import com.my.zl.console.entity.autocode.ZlProject;
import com.my.zl.console.entity.autocode.ZlTemplate;
import com.my.zl.console.entity.autocode.ZlTemplateDtl;
import com.my.zl.console.po.autocode.cfgGenerate.ZLCfgGenerateVo;
import com.my.zl.console.po.autocode.cfgGenerateDtl.ZLCfgGenerateDtlVo;
import com.my.zl.console.service.generator.IGeneratorService;
import com.my.zl.console.service.select.ISelectService;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.ZipUtil;
import cn.hutool.json.JSONUtil;


/**
 * 生成代码
 */
@Controller
@RequestMapping("/api/autocode/")
public class GeneratorController extends BaseController {
    protected final Logger LOGGER = LoggerFactory.getLogger(GeneratorController.class);
    
    private static Pattern RULE = Pattern.compile("(\\[.*?\\])");//截取条件
    
    @Autowired
    private IGeneratorService generatorService;
    @Autowired
    private Map<String,ReaderData<ZLConfig>> readerMap;
    @Autowired
    private ISelectService selectService;
    @Autowired
    private MyselfProperties myselfProperties;
    
    /**
     * 同步表数据
     **/
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value= "/loadtable", method = RequestMethod.POST)
    public ResDTO<ResLoadTableDTO> autocodeLoadtable(@RequestBody ReqDTO<ReqLoadTableDTO> reqInfo) throws Exception {
        ReqLoadTableDTO reqData = reqInfo.getReqData();
        ResLoadTableDTO resDTO = new ResLoadTableDTO();
        
        //配置
        ZLConfig iConfig = new ZLConfig();
        iConfig.setQueryType(reqData.getQueryType());
        iConfig.setLoadSourceType(reqData.getLoadSourceType());
        iConfig.setLoadTables(StrUtil.splitTrim(reqData.getLoadTables(), ","));
        iConfig.setLoadSeqs(StrUtil.splitTrim(reqData.getLoadSeqs(), ","));
        iConfig.setProjectId(reqData.getProjectId());
        iConfig.setLoadType(reqData.getLoadType());
        
        //查询基本设置
        generatorService.queryProjectTableConfig(reqInfo, iConfig);
        
        if(("database".equals(iConfig.getLoadType()) && StringUtils.isBlank(iConfig.getJdbcUrl())) 
                && ("pdm".equals(iConfig.getLoadType()) && StringUtils.isBlank(iConfig.getPdmPath()))
                && (StringUtils.isBlank(iConfig.getSqlPath()))){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
       
        if(readerMap.get(iConfig.getLoadType()+"Reader") == null){
            LOGGER.info("未实现当前数据库或文件解析接口");
            throw new BizException(GlobalEnum.METHOD_NOT_IMPLEMENTED);
        }
        readerMap.get(iConfig.getLoadType()+"Reader").parseData(iConfig);
        if("database".equals(iConfig.getLoadType()) || "pdm".equals(iConfig.getLoadType()) || "sql".equals(iConfig.getLoadType())){
            //同步表
            resDTO = generatorService.doInitialTables(reqInfo,iConfig);
        }else{
           //同步对象
            resDTO = generatorService.doInitialTables(reqInfo,iConfig);
        }
        
        
        return successDATA(resDTO);
    }
    
    /**
     * 传项目文件
     * @param reqInfo
     * @param fileObj
     * @return
     * @throws Exception
     */
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value = "/uploadproject", method = RequestMethod.POST)
    public ResDTO<ResUploadProjectDTO> autocodeUploadProjectFile(ReqUploadProjectDTO reqInfo , MultipartFile fileObj) throws Exception {
        ResUploadProjectDTO resDTO = new ResUploadProjectDTO();
        
        if(fileObj==null || fileObj.isEmpty() || StringUtils.isBlank(myselfProperties.getAutocodePathMajor())){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        String fileExt = FileUtil.extName(fileObj.getResource().getFilename());
        if(!"zip".equals(fileExt)  && !"pdm".equals(fileExt) && !"txt".equals(fileExt) && !"java".equals(fileExt)
                && !"sql".equals(fileExt)){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        String separatorStr = File.separator;
        
        boolean pdmFlag = "1".equals(reqInfo.getFileType())? true : false;
        
        ZlProject projectRecord = selectService.queryProject(reqInfo.getProjectId());
        
        String path = pdmFlag?projectRecord.getPdmPath() : projectRecord.getSqlPath();
        
        //不能丢失目录，否则会会删除目录下的文件
        if(StringUtils.isBlank(path)){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        if("zip".equals(fileExt)){
            File newFile = new File(path);
            if(newFile.exists() && newFile.isDirectory()){
                FileUtil.clean(newFile);
            }
            ZipUtil.unzip(fileObj.getInputStream(),newFile,CharsetUtil.CHARSET_UTF_8);
        }else{
            //放到指定文件
            if(!path.endsWith("\\") && !path.endsWith("/")){
                path = path + separatorStr;
            }
            FileUtil.writeFromStream(fileObj.getInputStream(), path +fileObj.getOriginalFilename());
        }
        
        return successDATA(resDTO);
    }
    
    
    /**
     * 传模板文件
     * @param reqInfo
     * @param fileObj
     * @return
     * @throws Exception
     */
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value = "/uploadtemplate", method = RequestMethod.POST)
    public ResDTO<ResLoadTemplateDTO> autocodeUploadTemplateFile(ReqLoadTemplateDTO reqInfo , MultipartFile fileObj) throws Exception {
        ResLoadTemplateDTO resDTO = new ResLoadTemplateDTO();
        
        if(fileObj==null || fileObj.isEmpty() || StringUtils.isBlank(myselfProperties.getAutocodePathMajor())){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        String fileExt = FileUtil.extName(fileObj.getResource().getFilename());
        if(!"zip".equals(fileExt) && !"btl".equals(fileExt) && !"vtl".equals(fileExt) && !"ftl".equals(fileExt)
                && !"ejy".equals(fileExt)){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        ZlTemplate tmpleteRecord = selectService.queryTemplate(reqInfo.getTemplateId());
        
        String separatorStr = File.separator;
        String path = tmpleteRecord.getTemplatePath();
        
        //不能丢失目录，否则会会删除目录下的文件
        if(StringUtils.isBlank(path)){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        if("zip".equals(fileExt)){
            File newFile = new File(path);
            if(newFile.exists() && newFile.isDirectory()){
                FileUtil.clean(newFile);
            }
            ZipUtil.unzip(fileObj.getInputStream(),newFile,CharsetUtil.CHARSET_UTF_8);
        }else{
            //放到指定文件
            if(!path.endsWith("\\") && !path.endsWith("/")){
                path = path + separatorStr;
            }
            FileUtil.writeFromStream(fileObj.getInputStream(), path +fileObj.getOriginalFilename());
        }
        
        return successDATA(resDTO);
    }
    /**
     * 同步模板
     **/
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value = "/loadtemplate", method = RequestMethod.GET)
    public ResDTO<ResLoadTemplateDTO> autocodeLoadTemplate(ReqLoadTemplateDTO reqInfo) throws Exception {
        
        ResLoadTemplateDTO resDTO = new ResLoadTemplateDTO();
        ZlTemplate tmpleteRecord = selectService.queryTemplate(reqInfo.getTemplateId());
        
        List<TemplateDtlVO> templateDtlList = new ArrayList<>();
        if(StringUtils.isNotBlank(tmpleteRecord.getTemplatePath())){
            File file = new File(tmpleteRecord.getTemplatePath());
            if(file.exists() && file.isDirectory()){
               File[] list = file.listFiles();
               for(File x : list){
                   if(x.exists() && x.isFile()){
                     String fileNameFull = FileUtil.getName(x);
                     String filemaneStr = StrUtil.stripIgnoreCase(fileNameFull, null, "."+FileUtil.extName(x));
                       
                       
                     TemplateDtlVO vo = new TemplateDtlVO();
                     vo.setFileTitle(filemaneStr.replaceAll("\\[.*\\]", "").trim());
                     vo.setFileName(fileNameFull);
                     vo.setOutputType("1");
                     vo.setOrderNum(0L);
                     vo.setProjectId(tmpleteRecord.getProjectId());
                     vo.setModuleId(tmpleteRecord.getModuleId());
                     vo.setTemplateId(tmpleteRecord.getTemplateId());
                     vo.setTemplateFileId(IdUtil.fastSimpleUUID());
                     //拆分
                     if(filemaneStr.contains("[")&&filemaneStr.contains("]")){
                         Matcher m = RULE.matcher(filemaneStr);
                         if(m.find()){
                             String tmpStr  = m.group().replaceAll("\\[|\\]", "");
                             String[] parr = tmpStr.split(",");
                             for(int i=0;i<parr.length && i<4;i++){
                                 if(StringUtils.isNotBlank(parr[i])){
                                     if(i==0){
                                         vo.setQuoteTag(parr[i]);
                                     }else if(i==1){
                                         vo.setOutputFileFormat(parr[i]);
                                     }else if(i==2){
                                         vo.setOutputType(parr[i]);
                                         if("99".equals(parr[i])){
                                             vo.setQuoteTag("N");
                                             vo.setOutputFileFormat("N");
                                         }
                                     }else if(i==3){
                                         vo.setOrderNum(Long.valueOf(parr[i]));
                                     }
                                 }
                             }
                         }
                     }
                     
                     templateDtlList.add(vo);
                  }
               }
            }
        }
        resDTO.setTemplateDtlList(templateDtlList);
        return successDATA(resDTO);
    }
    
    /**
     * 保存模板数据
     **/
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value= "/savetemplate", method = RequestMethod.POST)
    public ResDTO<ResLoadTemplateDTO> autocodeSaveTemplate(@RequestBody ReqDTO<ReqLoadTemplateDTO> reqInfo) throws Exception {
        ReqLoadTemplateDTO reqData = reqInfo.getReqData();
        
        ResLoadTemplateDTO resDTO  = generatorService.doInitialTemplateDtl(reqInfo);
        
        return successDATA(resDTO);
    }
    
    
    /**
     * 获取模板文件内容
     **/
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value= "/getTemplateContent", method = RequestMethod.GET)
    public ResDTO<ResTemplateContentDTO> autocodeGetTemplateContent(ReqTemplateContentDTO reqData) throws Exception {
        
        ResTemplateContentDTO resDTO = new ResTemplateContentDTO();
        
        ZlTemplateDtl templateDtlRecord = selectService.queryTemplateDtl(reqData.getTemplateFileId());
        ZlTemplate templateRecord = selectService.queryTemplate(templateDtlRecord.getTemplateId());
        ZlProject projectRecord = selectService.queryProject(templateRecord.getProjectId());
        String path = templateRecord.getTemplatePath() + templateDtlRecord.getFileName();
        String fileContent =  FileUtil.readString(path, projectRecord.getCharacterEncoding());
        resDTO.setFileContent(fileContent);
        
        return successDATA(resDTO);
    }
    /**
     * 保存模板文件内容
     **/
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value= "/saveTemplateContent", method = RequestMethod.POST)
    public ResDTO<ResTemplateContentDTO> autocodeSaveTemplateContent(@RequestBody ReqDTO<ReqTemplateContentDTO> reqInfo) throws Exception {
        ReqTemplateContentDTO reqData = reqInfo.getReqData();
        ResTemplateContentDTO resDTO  = new ResTemplateContentDTO();
        
        ZlTemplateDtl templateDtlRecord = selectService.queryTemplateDtl(reqData.getTemplateFileId());
        ZlTemplate templateRecord = selectService.queryTemplate(templateDtlRecord.getTemplateId());
        ZlProject projectRecord = selectService.queryProject(templateRecord.getProjectId());
        String path = templateRecord.getTemplatePath() + templateDtlRecord.getFileName();
        FileUtil.writeString(reqData.getFileContent(), path, projectRecord.getCharacterEncoding());
        
        return successDATA(resDTO);
    }
    
    /**
     * 代码生成
     * @param reqInfo
     * @return
     * @throws Exception
     */
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value = "/generator", method = RequestMethod.POST)
    public ResDTO<ResCodeGenereatorDTO> autocodeGenerator(@RequestBody ReqDTO<ReqCodeGenereatorDTO> reqInfo) throws Exception {
        ReqCodeGenereatorDTO reqData = reqInfo.getReqData();
        ResCodeGenereatorDTO  resDTO = new ResCodeGenereatorDTO();
        
        //直接读取最终配置
        ZLCfgGenerateVo cfgGenerateData = generatorService.queryCfgGenerate(reqInfo);
        
        if(StringUtils.isBlank(cfgGenerateData.getCfgGeneratePath())){
            throw new BizException(GlobalEnum.MISSING_FILE.getCode(), GlobalEnum.MISSING_FILE.getMsg());
        }
        
        List<ZLCfgGenerateDtlVo> generateDtlList = cfgGenerateData.getCfgGenerateDtlList();
        
        String usetime = "";
        if(generateDtlList!=null && generateDtlList.size()>0){
            List<CfgConfig> cfgConfigs = new ArrayList<>();
            List<String> hasKeys = new ArrayList<>();
            
            for(ZLCfgGenerateDtlVo x:generateDtlList){
                String configContent = x.getConfigContent();
                if(StringUtils.isNotBlank(configContent)){
                    CfgConfig cfgConfig = JSONUtil.toBean(configContent, CfgConfig.class);
                    
                    cfgConfig.setGenerateType(x.getGenerateType());
                    
                    cfgConfig.setCharacterEncoding(cfgGenerateData.getCharacterEncoding());
                    cfgConfig.setTemplatePath(cfgGenerateData.getTemplatePath());
                    cfgConfig.setCfgGeneratePath(cfgGenerateData.getCfgGeneratePath() + x.getCfgGenerateDtlId());
                    cfgConfig.setPrefixOverride(cfgGenerateData.getPrefixOverride());
                    cfgConfig.setSuffixOverride(cfgGenerateData.getSuffixOverride());
                    cfgConfig.setBasePackagePath(cfgGenerateData.getBasePackagePath());
                    cfgConfig.setOutputPackagePath(cfgGenerateData.getOutputPackagePath());
                    cfgConfig.setOutputRootPath(cfgGenerateData.getOutputRootPath());
                    cfgConfig.setDatabaseType(cfgGenerateData.getDatabaseType());
                    cfgConfig.setTagAuthor(cfgGenerateData.getTagAuthor());
                    cfgConfig.setTagExplain1(cfgGenerateData.getTagExplain1());
                    cfgConfig.setTagExplain2(cfgGenerateData.getTagExplain2());
                    cfgConfig.setProjectTitle(cfgGenerateData.getProjectTitle());
                    cfgConfig.setModuleTitle(cfgGenerateData.getModuleTitle());
                    
                    cfgConfigs.add(cfgConfig);
                    
                    //联动不能相同
                    if("2".equals(x.getGenerateType())){
                        if(!hasKeys.contains(x.getModuleKey())){
                            hasKeys.add(x.getModuleKey());
                        }else{
                            resDTO.setSameFlag("1");
                            return errorDATA(resDTO);
                        }
                    }
                }
            }
            usetime = ZLGenerator.entry(cfgConfigs);
        }
        
        List<FileListDTO> fileList = new ArrayList<>();
        Map<String,List<String>> hasFileKey = new HashMap<>();
        int fi= 0;
        for(ZLCfgGenerateDtlVo cfgGenerateDtl : generateDtlList){
            FileListDTO pVO = new FileListDTO();
            pVO.setType("0");
            pVO.setFileName(cfgGenerateDtl.getModuleKeyName());
            pVO.setFilePath(cfgGenerateDtl.getModuleKey());
            pVO.setParentId(null);
            pVO.setId(cfgGenerateDtl.getModuleKey().replace(".", "")+fi);
            fileList.add(pVO);
            
            //获取目录压缩并下载
            File f1 = new File(cfgGenerateData.getCfgGeneratePath() + cfgGenerateDtl.getCfgGenerateDtlId());
            if(f1.exists() && f1.isDirectory()){
                String extType =".zip";
                String filename = cfgGenerateDtl.getCfgGenerateDtlId() + extType;
                File zipFile = FileUtil.file(cfgGenerateData.getCfgGeneratePath() + filename);
                ZipUtil.zip(zipFile,CharsetUtil.CHARSET_UTF_8, false, f1);
                
                hasFileKey.put(pVO.getId(), new ArrayList<>());
                
                List<File> allfiles = FileUtil.loopFiles(f1);
                for (int i = 0; i < allfiles.size(); i++) {
                    File f = allfiles.get(i);
                    
                    String cpid =  f.getParent().replace(f1.getPath(), "").replace(File.separator, ".").substring(1);
                    
                    //全树形路径
                    String[] tpaths = cpid.split("\\.");
                    String pstr = "";
                    for(String tp : tpaths){
                        String selfpath = pstr+File.separator+tp;
                        String selfid = (selfpath+fi).replace(File.separator, "_").substring(1);
                        if(!hasFileKey.get(pVO.getId()).contains(selfid)){
                            hasFileKey.get(pVO.getId()).add(selfid);
                            
                            FileListDTO fVO = new FileListDTO();
                            if(f.getName().toLowerCase().endsWith(".java")){
                                fVO.setType("1");
                            }else if(f.getName().toLowerCase().endsWith(".xml")){
                                fVO.setType("3");
                            }else{
                                fVO.setType("4");
                            }
                            fVO.setFileName(tp);
                            fVO.setFilePath(selfpath);
                            fVO.setParentId(pstr == ""? pVO.getId(): (pstr+fi).replace(File.separator, "_").substring(1));
                            fVO.setId(selfid);
                            fileList.add(fVO);
                        }
                        pstr = selfpath;
                    }
                    FileListDTO pVO2 = new FileListDTO();
                    
                    pVO2.setType("2");
                    pVO2.setFileName(f.getName());
                    pVO2.setFilePath(f.getPath().replace(f1.getPath(), ""));
                    pVO2.setParentId(cpid.replace(".", "_")+fi);
                    pVO2.setId(f.getName().replace(".", "_")+fi);
                    pVO2.setFileContent(FileUtil.readString(f, "UTF-8"));
                    fileList.add(pVO2);
                }
                fi++;
            }
        }
        
        if(fileList !=null && fileList.size() > 0){
            fileList = fileList.stream().sorted(Comparator.comparing(FileListDTO::getType)).collect(Collectors.toList());
        }
            
        resDTO.setCfgGenerateId(cfgGenerateData.getCfgGenerateId());
        resDTO.setUseTime(usetime);
        resDTO.setFileList(fileList);
        
        return successDATA(resDTO);
    }
    
    @NoLogAnnotation
    @RequestMapping(value = "/generatorDownload", method = {RequestMethod.GET,RequestMethod.POST})
    public void autocodeGeneratorDownload(HttpServletRequest request, HttpServletResponse response, ReqCodeGenereatorDTO reqData) throws Exception {
        
        ReqDTO<ReqCodeGenereatorDTO> reqInfo = new ReqDTO<ReqCodeGenereatorDTO>();
        reqInfo.setReqData(reqData);
        
        ZLCfgGenerateVo cfgGenerateData = generatorService.queryCfgGenerate(reqInfo);
        
        if(cfgGenerateData == null){
            return;
        }
        String cfgGenerateDtlTitle = "";
        if(cfgGenerateData.getCfgGenerateDtlList()!=null && cfgGenerateData.getCfgGenerateDtlList().size()>0){
            cfgGenerateDtlTitle = cfgGenerateData.getCfgGenerateDtlList().get(0).getModuleKeyName();
        }
        String extType =".zip";
        String filename = cfgGenerateData.getCfgGenerateTitle()+"-"+cfgGenerateDtlTitle +"-"+cfgGenerateData.getCfgGenerateDtlList().get(0).getCfgGenerateDtlId();
        String encoding = request.getCharacterEncoding();
        if(StringUtils.isNotBlank(encoding)){
            filename = URLEncoder.encode(filename,encoding);
        }else{
            //默认编码是utf-8
            filename = URLEncoder.encode(filename,CharsetUtil.CHARSET_UTF_8.name());
        }
        filename = filename + extType;
        response.setHeader("content-disposition","attachment;fileName="+filename);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding(CharsetUtil.CHARSET_UTF_8.name());
//        response.addHeader("Content-Length", "");
        
        String filename2 = cfgGenerateData.getCfgGenerateDtlList().get(0).getCfgGenerateDtlId() + extType;
        File zipFile = new File(cfgGenerateData.getCfgGeneratePath() + filename2);
        if(zipFile.exists() && zipFile.isFile()){
            InputStream in = new FileInputStream(zipFile); //获取下载文件的输入流
            
            int count =0;
            byte[] by = new byte[1024];
            OutputStream out=  response.getOutputStream();
            while((count=in.read(by))!=-1){
               out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            in.close();
            out.flush();
            out.close();
        }
    }
    
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping("/getTableData")
    public ResDTO<ResLoadTableDTO> getTableData(@RequestBody ReqDTO<ReqLoadTableDTO> reqInfo) throws Exception {
        ReqLoadTableDTO reqData = reqInfo.getReqData();
        ResLoadTableDTO resDTO = new ResLoadTableDTO();
        
        //配置
        ZLConfig iConfig = new ZLConfig();
        iConfig.setQueryType(reqData.getQueryType());
        iConfig.setLoadSourceType(reqData.getLoadSourceType());
        iConfig.setLoadTables(StrUtil.splitTrim(reqData.getLoadTables(), ","));
        iConfig.setLoadSeqs(StrUtil.splitTrim(reqData.getLoadSeqs(), ","));
        iConfig.setProjectId(reqData.getProjectId());
        iConfig.setLoadType(reqData.getLoadType());
        
        //查询基本设置
        generatorService.queryProjectTableConfig(reqInfo, iConfig);
        
        if(("database".equals(iConfig.getLoadType()) && StringUtils.isBlank(iConfig.getJdbcUrl())) 
               && ("pdm".equals(iConfig.getLoadType()) && StringUtils.isBlank(iConfig.getPdmPath()))
               && (StringUtils.isBlank(iConfig.getSqlPath()))){
            throw new BizException(GlobalEnum.MISSING_FILE);
        }
        
        if(readerMap.get(iConfig.getLoadType()+"Reader") == null){
            LOGGER.info("未实现当前数据库或文件解析接口");
            throw new BizException(GlobalEnum.METHOD_NOT_IMPLEMENTED);
        }
        
        Map<String,Object> datas = readerMap.get(iConfig.getLoadType()+"Reader").getData(iConfig);
        
        resDTO.setDataInfos(datas);
        return successDATA(resDTO);
    }
    
    
    /**
     * 获取文件信息
     */
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value="/getProjectFiles")
    public ResDTO<ResProjectFileDTO> getProjectFileList(ReqProjectFileDTO reqInfo) throws Exception{
        ResProjectFileDTO resDTO = new ResProjectFileDTO();
        
        List<FileListDTO> fileList = new ArrayList<>();
        if(reqInfo.getTemplateId()!=null){
            ZlTemplate templateRecord = selectService.queryTemplate(reqInfo.getTemplateId());
            if(StringUtils.isNotBlank(templateRecord.getTemplatePath())){
                getFileInfos("template", "模板", templateRecord.getTemplatePath(), fileList);
            }
        }
        else if(reqInfo.getProjectId()!=null){
            ZlProject projectRecord = selectService.queryProject(reqInfo.getProjectId());
            String pdmPath = projectRecord.getPdmPath();
            String sqlPath =  projectRecord.getSqlPath();
            
            if(StringUtils.isNotBlank(pdmPath)){
                getFileInfos("pdm", "pdm", pdmPath, fileList);
            }
            
            if(StringUtils.isNotBlank(sqlPath)){
                getFileInfos("text", "sql/javabean/text", sqlPath, fileList);
            }
        }
        
        resDTO.setFileList(fileList);
        return successDATA(resDTO);
    }
    private void getFileInfos(String pid,String text,String pPath,List<FileListDTO> fileList){
        FileListDTO pVO1 = new FileListDTO();
        pVO1.setType("0");
        pVO1.setFileName(text);
        pVO1.setFilePath("");
        pVO1.setParentId("");
        pVO1.setId(pid);
        fileList.add(pVO1);
        
        List<File> allfiles2 = FileUtil.loopFiles(pPath);
        for (int i = 0; i < allfiles2.size(); i++) {
            File f = allfiles2.get(i);
            FileListDTO cVO = new FileListDTO();
            cVO.setType("2");
            cVO.setFileName(f.getName());
            cVO.setFilePath("");
            cVO.setParentId(pid);
            cVO.setId(StrUtil.uuid());
//            cVO.setFileContent(FileUtil.readString(f, "UTF-8"));
            fileList.add(cVO);
        }
    }
    
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value="/delProjectFiles", method = RequestMethod.POST)
    public ResDTO<ResProjectFileDTO> doDeleteProjectFileList(@RequestBody ReqDTO<ReqProjectFileDTO> reqData) throws Exception{
       ReqProjectFileDTO reqInfo = reqData.getReqData();
       ResProjectFileDTO resDTO = new ResProjectFileDTO();
       if(reqInfo.getTemplateId()!=null){
           ZlTemplate templateRecord = selectService.queryTemplate(reqInfo.getTemplateId());
           File file1 = new File(templateRecord.getTemplatePath()+reqInfo.getFileName());
           if(file1.exists() && file1.isFile()){
               FileUtil.del(file1);
           }
       }
       else if(reqInfo.getProjectId()!=null){
           ZlProject projectRecord = selectService.queryProject(reqInfo.getProjectId());
           String pdmPath = projectRecord.getPdmPath();
           String sqlPath =  projectRecord.getSqlPath();
           File file1 = new File(pdmPath+reqInfo.getFileName());
           File file2 = new File(sqlPath+reqInfo.getFileName());
           if(file1.exists() && file1.isFile()){
               FileUtil.del(file1);
           }else if(file2.exists() && file2.isFile()){
               FileUtil.del(file2);
           }
       }
       
       return successDATA(resDTO);
    }
    
    @NoLogAnnotation
    @RequestMapping(value = "/downloadProjectZip", method = {RequestMethod.GET,RequestMethod.POST})
    public void autocodeDownloadProojectZip(HttpServletRequest request, HttpServletResponse response, ReqUploadProjectDTO reqData) throws Exception {
        ZlProject projectInfo = selectService.queryProject(reqData.getProjectId());
        String path = reqData.getFileType().equalsIgnoreCase("pdm")?projectInfo.getPdmPath():projectInfo.getSqlPath();
        String extType =".zip";
        String filename = projectInfo.getProjectTitle()+"-"+projectInfo.getProjectId();
        String encoding = request.getCharacterEncoding();
        if(StringUtils.isNotBlank(encoding)){
            filename = URLEncoder.encode(filename,encoding);
        }else{
            //默认编码是utf-8
            filename = URLEncoder.encode(filename,CharsetUtil.CHARSET_UTF_8.name());
        }
        filename = filename + extType;
        response.setHeader("content-disposition","attachment;fileName="+filename);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding(CharsetUtil.CHARSET_UTF_8.name());
        
        File zipFile = FileUtil.createTempFile(new File(path).getParentFile());
        ZipUtil.zip(zipFile,CharsetUtil.CHARSET_UTF_8, false, new File(path));
        if(zipFile.exists() && zipFile.isFile()){
            InputStream in = new FileInputStream(zipFile); //获取下载文件的输入流
            
            int count =0;
            byte[] by = new byte[1024];
            OutputStream out=  response.getOutputStream();
            while((count=in.read(by))!=-1){
               out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            in.close();
            out.flush();
            out.close();
        }
    }
    @NoLogAnnotation
    @RequestMapping(value = "/downloadTemplateZip", method = {RequestMethod.GET,RequestMethod.POST})
    public void autocodeDownloadTemplateZip(HttpServletRequest request, HttpServletResponse response, ReqLoadTemplateDTO reqData) throws Exception {
        ZlTemplate templateInfo = selectService.queryTemplate(reqData.getTemplateId());
        String path = templateInfo.getTemplatePath();
        String extType =".zip";
        String filename = templateInfo.getTemplateTitle()+"-"+templateInfo.getTemplateId();
        String encoding = request.getCharacterEncoding();
        if(StringUtils.isNotBlank(encoding)){
            filename = URLEncoder.encode(filename,encoding);
        }else{
            //默认编码是utf-8
            filename = URLEncoder.encode(filename,CharsetUtil.CHARSET_UTF_8.name());
        }
        filename = filename + extType;
        response.setHeader("content-disposition","attachment;fileName="+filename);
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding(CharsetUtil.CHARSET_UTF_8.name());
        
        File zipFile = FileUtil.createTempFile(new File(path).getParentFile());
        ZipUtil.zip(zipFile,CharsetUtil.CHARSET_UTF_8, false, new File(path));
        if(zipFile.exists() && zipFile.isFile()){
            InputStream in = new FileInputStream(zipFile); //获取下载文件的输入流
            
            int count =0;
            byte[] by = new byte[1024];
            OutputStream out=  response.getOutputStream();
            while((count=in.read(by))!=-1){
               out.write(by, 0, count);//将缓冲区的数据输出到浏览器
            }
            in.close();
            out.flush();
            out.close();
        }
    }
    
    /** 用于通过用可视化数据处理*/
    @ResponseBody
    @NoLogAnnotation
    @RequestMapping(value = "/templateViewShow", method = RequestMethod.POST)
    public ResDTO<ResTemplateViewShowDTO> autocodeTemplateViewShow(@RequestBody ReqDTO<ReqTemplateViewShowDTO> reqInfo) throws Exception {
        ReqTemplateViewShowDTO reqData = reqInfo.getReqData();
        ResTemplateViewShowDTO resDTO = new ResTemplateViewShowDTO();
        
        List<CfgMethodEntity> entityData = reqData.getEntitys();
        
        if(entityData != null && entityData.size()>0){
            
            List<CfgMethodEntity> orderlist = ZLGenerator.doHandleEntityOrder(entityData);
            
            Map<String,List<CfgMethodEntity>> grouplt =  new LinkedHashMap<>();
            Map<String,String> groupnm = new LinkedHashMap<>();
            ZLGenerator.doHandleEntityGroup(orderlist, grouplt, groupnm);
            
            Map<String, Object> rootMap = new HashMap<>();
            Map<String, Object> orderEntitys = new HashMap<>();
            Map<String, Object> groupEntitys = new HashMap<>();
            Map<String, Object> groupNames = new HashMap<>();
            //保持模板同步结构
            orderEntitys.put("dto", orderlist);
            groupEntitys.put("dto", grouplt);
            groupNames.put("dto", groupnm);
            rootMap.put("orderEntitys", orderEntitys);
            rootMap.put("groupEntitys", groupEntitys);
            rootMap.put("groupNames", groupNames);
            rootMap.put("viewEditType", reqData.getViewEditType());
            
            FreemarkerTool.initFreemarker2("/template/autocode");
            
            String htmlStr = FreemarkerTool.processString(rootMap, "easyui-index.ftl", "UTF-8");
            resDTO.setHtmlStr(htmlStr);
        }
        //读取模板
        
        return successDATA(resDTO);
    }
    
    @ResponseBody
    @RequestMapping("/test")
    public Object test() throws Exception {
        //加载原始数据
        ZLConfig iConfig = new ZLConfig();
        readerMap.get("databaseReader").parseData(iConfig);
        
        return successDATA(null);
    }
    
    
    public static String getFileHeader(String filePath) {
        FileInputStream is = null;
        String value = null;
        try {
            is = new FileInputStream(filePath);
            byte[] b = new byte[4];
            /*
             * int read() 从此输入流中读取一个数据字节。 int read(byte[] b) 从此输入流中将最多 b.length
             * 个字节的数据读入一个 byte 数组中。 int read(byte[] b, int off, int len)
             * 从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
             */
            is.read(b, 0, b.length);
            value = bytesToHexString(b);
        } catch (Exception e) {
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (Exception e) {
                }
            }
        }
        return value;
    }
 
    /**
     * 将要读取文件头信息的文件的byte数组转换成string类型表示
     * 
     * @param src
     *            要读取文件头信息的文件的byte数组
     * @return 文件头信息
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }
//        System.out.println(builder.toString());
        return builder.toString();
    }
    
    public static void main(String[] args) throws Exception{
//       File f = new File("G:/个人测试数据库.pdm");
//        File f = new File("G:\\zlautocode\\[tag][0][xml]zl-xml.ftl");
//        System.out.println();
      
//    String time = DateTimeFormatter.ofPattern("yyyy-MM-dd").withLocale(Locale.SIMPLIFIED_CHINESE).withZone(ZoneId.systemDefault()).format(Instant.now());
//      System.out.println(time);
        
//        String configContent =FileUtil.readString(new File("F:/ZLworkspace8/ZLalldemo/ZL-autocode/src/main/webapp/static/ftl/json.txt"), "UTF-8");
        String configContent =FileUtil.readString(new File("D:/zlspace/workspace/ZLalldemo/ZL-autocode/src/main/webapp/static/ftl/json.txt"), "UTF-8");
        
        CfgConfig cfgConfig = JSONUtil.toBean(configContent,  CfgConfig.class);
        cfgConfig.setCharacterEncoding("UTF-8");
        cfgConfig.setTemplatePath("G:\\zlautocode\\templates\\047e87d5347d495aa78f69b3999fa6c3\\");
        cfgConfig.setCfgGeneratePath("G:\\zlautocode\\generates\\3c4bed4e87834bca9feba331379b4fb4\\3fb1f66fd9694226a23c68080a763084\\");
        cfgConfig.setBasePackagePath("com.my.zl");
        cfgConfig.setOutputPackagePath("console");
        cfgConfig.setOutputRootPath("z-easyui");
        cfgConfig.setPrefixOverride("^(ZL_|TBL)");
        cfgConfig.setSuffixOverride("I,zl");
        cfgConfig.setTagAuthor("zhouliang");
        cfgConfig.setTagExplain1("");
        cfgConfig.setTagExplain2("");
        cfgConfig.setGenerateType("2");
        
        List<CfgConfig> cfgConfigs = new ArrayList<>();
        cfgConfigs.add(cfgConfig);
//        ZLGenerator.entry(cfgConfigs);
    }
      
}
